package com.df.hitime.common;

import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description: 时间工具类
 * @Author: huangwl
 * @CreateDate: 2018/11/26 11:50
 */
public class DateUtils {

    /**
     * 两个时间相减得到秒数
     *
     * @param date1 被减数
     * @param date2 减数
     * @return
     */
    public static Integer subtract(Date date1, Date date2) {
        Long millisecond = date1.getTime() - date2.getTime();
        Integer seconds = Math.toIntExact((millisecond / 1000));
        return seconds;
    }

    public static void main(String[] args) throws Exception {
        Date date1 = new Date();
        Thread.sleep(3000);
        Date date2 = new Date();
        System.out.println(subtract(date2, date1));

    }

    public static String getNowDate(String format) {
        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public static String getNowDate(){
        return getNowDate("yyyy-MM-dd HH:mm:ss");
    }

    public static String dateFormat(Date date,String format){
        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String dateFormat(Date date){
        String format = "yyyy-MM-dd HH:mm:ss";
        return dateFormat(date,format);
    }

    public static Date addData(int num){
        Calendar cd = Calendar.getInstance();
        cd.setTime(new Date());
        cd.add(Calendar.DATE, num);//增加一天
        return cd.getTime();
    }
}
